<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="" xml:lang="">
  <head>
    <meta charset="utf-8" />
    <meta name="generator" content="pandoc" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1.0, user-scalable=yes"
    />
    <title>The_Python_RegEx_Cheat_Sheet_for_Budding_Programmers</title>
    <style type="text/css">
      code {
        white-space: pre-wrap;
      }
      span.smallcaps {
        font-variant: small-caps;
      }
      span.underline {
        text-decoration: underline;
      }
      div.column {
        display: inline-block;
        vertical-align: top;
        width: 50%;
      }
    </style>
  </head>
  <body>
    <h1 id="the-python-regex-cheat-sheet-for-budding-programmers">
      The Python RegEx Cheat Sheet for Budding Programmers
    </h1>
    <blockquote>
      <p>
        Use this list of Python regular expressions so that you can get better
        at using this versatile programming language.
      </p>
    </blockquote>
    <p>
      print()Display the result of a commandx=“Hello world”<br />
      print(x)
    </p>
    <p>output: Hello world</p>
    <p>input()Collect inputs from usersprint(input(“what is your name?”))</p>
    <p>output: what is your name?</p>
    <p>
      type()Find the type of a variablex=“Regular expressions”<br />
      type(x)
    </p>
    <p>output:</p>
    <p>len()Find the number of items in a variablelen([1, 2, 3])</p>
    <p>output: 3</p>
    <p>
      \Escape a character that changes the intent of a line of codeprint(“I want
      you to add\”\"")
    </p>
    <p>output: I want you to add""</p>
    <p>
      \nBreak a string character to start on the next lineprint(“This is a line
      \n This is a second line”)
    </p>
    <p>
      output:<br />
      This is a line<br />
      This is a second line
    </p>
    <p>
      def function_name(parameter):<br />
      commandsInitiate a function with an optional parameterdef yourName(x):<br />
      print(x+1)lambdaCall an anonymous functionadd_3_to = lambda y: y+3<br />
      print(add_3_to(4))
    </p>
    <p>output: 7</p>
    <p>
      returnReturn a result from a functiondef yourName(x):<br />
      return x+1classCreate a Python objectclass myClass:<br />
      def myFunc(x):def __init__Initialize the attrributes of a classclass
      myClass:<br />
      def __init__(self, attributes…)"__init__.pySave a file containing a module
      so that it’s read successfully in another Python fileRename a file
      containing a module as:
    </p>
    <p>"__init__.py</p>
    <p>int()Convert a variable to integerint(1.234)</p>
    <p>output: 1</p>
    <p>str()Convert a variable to stringstr(1.234)</p>
    <p>output: ‘1.234’</p>
    <p>float()Convert a variable to floatfloat(23)</p>
    <p>output: 23.0</p>
    <p>
      dict(Counter())Convert a list or a tupple into a dictionary after sorting
      with a Python built-in Counterfrom collections import Counter<br />
      dict(Counter([1,1,2,1,2,3,3,4]))
    </p>
    <p>output: {1: 3, 2: 2, 3: 2, 4: 1}</p>
    <p>
      round()Round up the output of an operation to the nearest whole
      numberround(23.445)
    </p>
    <p>output: 23</p>
    <p>
      round(operation or number, decimal places)Round up the output of an
      operation to a specific number of decimal placesround(23.4568, 2)
    </p>
    <p>output: 23.46</p>
    <p>
      if:Initiate a conditional statementif 2&lt;3:<br />
      print(“Two is smaller”)elif:Make a counterstatement when the if statement
      is Falseif 2&lt;3:<br />
      print(“Two is smaller”)<br />
      elif 2==3:<br />
      print(“Go on”)else:Make a final counterstatement if other conditions are
      Falseif 2&lt;3:<br />
      print(“Two is smaller”)<br />
      elif 2==3:<br />
      print(“Go on”)<br />
      else:<br />
      print(“Three is greater”)continueIgnore a condition and execute the rest
      of the loopa=[1, 4, -10, 6, 8]<br />
      for b in a:<br />
      if b&lt;=0:<br />
      continue<br />
      print(b)
    </p>
    <p>
      output:<br />
      1<br />
      4<br />
      6<br />
      8
    </p>
    <p>
      breakTerminate the flow of a loop with a given conditiona=[1, 4, -10, 6,
      8]<br />
      for b in a:<br />
      if b&gt;=6:<br />
      break<br />
      print(b)
    </p>
    <p>
      output:<br />
      1<br />
      4<br />
      -10
    </p>
    <p>
      passIgnore a set of prior instructionsfor b in a:<br />
      passtry, except<br />
      Try a block of code, else, raise a defined exceptiontry:<br />
      print(a)
    </p>
    <p>
      except:<br />
      print(“An error occured!”)
    </p>
    <p>output: An error occured!</p>
    <p>
      finallyExecute a final code when the try and the except blocks failtry:<br />
      print(a)
    </p>
    <p>
      except:<br />
      print(d)<br />
      finally:<br />
      print(“You can’t print an undefined variable”)
    </p>
    <p>output: You can’t print an undefined variable</p>
    <p>
      raise Exception()Raise an exception that stops the command when execution
      isn’t possiblea=7+2<br />
      if a&lt;10:<br />
      raise Exception(“Oh! You didn’t get a score of 10”)import xImport a whole
      module or libraryimport mathfrom x import yImport a library x from a file,
      or a class yfrom scipy.stats import modeasCustomize an expression to your
      preferred nameimport pandas as pdinCheck if a value is present in a
      variablex=[1, 4, 6, 7]<br />
      if 5 in x:<br />
      print(“There is a five”)<br />
      else:<br />
      print(“There is no five”)
    </p>
    <p>output: There is no five</p>
    <p>
      isCheck if two variables refer to a single elementx=[1, 4, 6, 7]<br />
      x=b<br />
      print(x is b)<br />
      TrueNoneDeclare a null valuex=None&lt;Check if one value is lesser than
      another5&lt;10
    </p>
    <p>output: True</p>
    <p>&gt;Check if one value is more than another5&gt;10</p>
    <p>output: False</p>
    <p>&lt;=Check if a value is lesser or equal to another2*2&lt;=3</p>
    <p>output: False</p>
    <p>&gt;=Check if a value is greater or equal to another2*2&gt;=3</p>
    <p>output: True</p>
    <p>"==Check if a value is exactly equal to the other3==4</p>
    <p>ouput: False</p>
    <p>!=Ascertain that a value is not equal to the other3!=4</p>
    <p>ouput: True</p>
    <p>
      import reImport Python’s built-in regular expressionsimport re<br />
      re.findall(“strings”, variable)a|bCheck if either of two elements are
      present in a stringimport re<br />
      someText=“Hello regular expression”<br />
      a=re.findall(“regular|Hello”, someText)<br />
      print(a)
    </p>
    <p>output: [‘Hello’, ‘regular’]</p>
    <p>
      string<span class="math inline"
        ><span class="math inline"
          >$Check if a variable ends with a set of stringsimport re
          someText="Hello regular expression" a=re.findall("expression$</span
        ></span
      >", someText)
    </p>
    <p>output: [‘expression’]</p>
    <p>
      ^stringCheck if a variable starts with a set of stringsimport re<br />
      someText=“Hello regular expression”<br />
      a=re.findall(“^Hello”, someText)<br />
      print(a)
    </p>
    <p>output: [‘Hello’]</p>
    <p>
      string.index()Check the index position of a string charactera= “Hello
      World”<br />
      a.index(‘H’)
    </p>
    <p>output: 0</p>
    <p>
      string.capitalize()Capitalize the first character in a set of stringsa=
      “Hello World”<br />
      a.capitalize()
    </p>
    <p>output: ‘Hello world’</p>
    <p>
      string.swapcase()Print the first letter of each word as a lower case and
      the others as upper casea= “Hello World”<br />
      a.swapcase()
    </p>
    <p>
      output:<br />
      ‘hELLO wORLD’
    </p>
    <p>
      string.lower()Convert all the strings to a lowercasea= “Hello World”<br />
      a.lower()
    </p>
    <p>output: ‘hello world’</p>
    <p>
      string.upper()Convert all strings to uppercasea= “Hello World”<br />
      a.upper()
    </p>
    <p>output: ‘HELLO WORLD’</p>
    <p>
      string.startswith()Check if a string starts with a particular charactera=
      “Hello World”<br />
      a.startswith(‘a’)
    </p>
    <p>output: False</p>
    <p>
      string.endswith()Check if a string ends with a particular charactera=
      “Hello World”<br />
      a.endswith(‘d’)
    </p>
    <p>output: True</p>
    <p>
      string.split()Separate each word into a lista= “Hello World”<br />
      a.split()
    </p>
    <p>output: [‘Hello’, ‘world’]</p>
    <p>
      strings {}’.format()Display an output as stringa=3+4<br />
      print(“The answer is {}”.format(a))
    </p>
    <p>output: The answer is 7</p>
    <p>
      is not NoneCheck if the value of a variable is not emptydef
      checknull(a):<br />
      if a is not None:<br />
      return “its full!”<br />
      else:<br />
      return “its empty!”x%yFind the remainder (modulus) of a division9%4
    </p>
    <p>output: 1</p>
    <p>x//yFind the quotient of a division9//4</p>
    <p>output: 2</p>
    <p>
      “=Assign a value to a variablea={1:5, 3:4}”+Add elements together[“a two”]
      + [“a one”]
    </p>
    <p>output: [‘a two’, ‘a one’]</p>
    <p>1+3</p>
    <p>output=4</p>
    <p>"-Find the difference between a set of numbers3-4</p>
    <p>output=-1</p>
    <p>"*Find the product of a set of numbers3*4</p>
    <p>output:12</p>
    <p>
      a+=xAdd x to variable a without assigning its value to a new
      variablea=2<br />
      a+=3
    </p>
    <p>output: 5</p>
    <p>
      a-=xSubsract x from variable a without assigning it to a new
      variablea=3<br />
      a-=2
    </p>
    <p>output: 1</p>
    <p>
      a*=xFind the product of variable a and x without assigning the resullt to
      a new variablea=[1, 3, 4]<br />
      a*=2
    </p>
    <p>output: [1, 3, 4, 1, 3, 4]</p>
    <p>x**yRaise base x to power y2**3</p>
    <p>output: 8</p>
    <p>pow(x, y)Raise x to the power of ypow(2, 3)</p>
    <p>output: 8</p>
    <p>abs(x)Convert a negative integer to its absolute valueabs(-5)</p>
    <p>output: 5</p>
    <p>x**(1/nth)Find the nth root of a number8**(1/3)</p>
    <p>output: 2</p>
    <p>
      a=b=c=d=xAssign the same value to multiple variablesa=b=c=d=“Hello
      world”x, y = y, xSwap variablesx = [1, 2]<br />
      y = 3<br />
      x, y = y, x<br />
      print(x, y)
    </p>
    <p>
      output:<br />
      3 [1, 2]
    </p>
    <p>
      forLoop through the elements in a variablea=[1, 3, 5]<br />
      for b in a:<br />
      print(b, “x”, “2”, “=”, b*2)
    </p>
    <p>
      output:<br />
      1 x 2 = 2<br />
      3 x 2 = 6<br />
      5 x 2 = 10
    </p>
    <p>
      whileKeep looping through a variable, as far as a particular condition
      remains True a=4<br />
      b=2<br />
      while b&lt;=a:<br />
      print(b, “is lesser than”, a)<br />
      b+=1
    </p>
    <p>
      output:<br />
      2 is lesser than 4<br />
      3 is lesser than 4<br />
      4 is lesser than 4
    </p>
    <p>
      range()Create a range of positive integers between x and yx=range(4)<br />
      print(x)<br />
      range(0, 4)<br />
      for b in x:<br />
      print(b)
    </p>
    <p>
      output:<br />
      0<br />
      1<br />
      2<br />
      3
    </p>
    <p>sum()Iterate through the elements in a listprint(sum([1, 2, 3]))</p>
    <p>output:6</p>
    <p>
      sum(list, start)Return the sum of a list with an added
      elementprint(sum([1, 2, 3], 3))
    </p>
    <p>output: 9</p>
    <p>
      []Make a list of elementsx=[‘a’, 3, 5, ‘h’, [1, 3, 3], {‘d’:3}]()Create a
      tupple—tupples are immutablex=(1, 2, ‘g’, 5){}Create a dictionarya={‘x’:6,
      ‘y’:8}x[a:b]Slice through a listx=[1, 3, 5, 6]<br />
      x[0:2]
    </p>
    <p>output: [1, 3]</p>
    <p>
      x[key]Get the value of a key in dictionary xa={‘x’:6, ‘y’:8}<br />
      print(a[‘x’])
    </p>
    <p>output: 6</p>
    <p>
      x.append()Add a list of values to an empty listx=[1]<br />
      x.append([1,2,3])<br />
      print(x)
    </p>
    <p>output: [1, [1,2,3]]</p>
    <p>
      x.extend()Add a list of values to continue an existing list without
      necessarily creating a nested listx=[1,2]<br />
      x.extend([3,4,6,2])<br />
      print(x)
    </p>
    <p>
      output:<br />
      [1, 2, 3, 4, 6, 2]
    </p>
    <p>
      del(x[a:b])Delete an item completely from a list at a specific
      indexx=[1,2,3,5]<br />
      del(x[0:2])<br />
      print(x)
    </p>
    <p>output: [2,3,5]</p>
    <p>
      del(x[key])Delete a key and a value completely from a dictionary at a
      specific indexy={1:3, 2:5, 4:6, 8:2}<br />
      del(y[1], y[8])<br />
      print(y)
    </p>
    <p>output= {2:5, 4:6}</p>
    <p>
      dict.pop()Pop out the value of a key and remove it from a dictionary at a
      specific indexa={1:3, 2:4, 5:6}<br />
      a.pop(1)
    </p>
    <p>output: 3</p>
    <p>
      dict.popitem()Pop out the last item from a dictionary and delete ita={1:2,
      4:8, 3:5}<br />
      a.popitem()
    </p>
    <p>
      output: (3, 5)<br />
      print(a)<br />
      output: {1:2, 4:8}
    </p>
    <p>
      list.pop()Pop out a given index from a list and remove it from a lista=[1,
      3, 2, 4, 1, 6, 6, 4]<br />
      a.pop(-2)
    </p>
    <p>
      output: 6<br />
      print(a)<br />
      output: [1, 3, 2, 4, 1, 6, 4]
    </p>
    <p>
      clear()Empty the elements of a list or a dictionaryx=[1, 3, 5]<br />
      x.clear()<br />
      print(x)
    </p>
    <p>output: []</p>
    <p>
      remove()Remove an item from a listx=[1, 5, 6, 7]<br />
      x.remove(1)
    </p>
    <p>output: [5, 6, 7]</p>
    <p>
      insert()Insert elements into a llistx=[3, 5, 6]<br />
      x.insert(1, 4)<br />
      print(x)
    </p>
    <p>output: [1, 4, 3, 5, 6]</p>
    <p>
      sort(reverse=condition)Reverse the direction of the elements in a
      listx=[1, 3, 5, 6]<br />
      x.sort(reverse=True)<br />
      print(x)
    </p>
    <p>output: [6, 5, 3, 1]</p>
    <p>
      update()Update a dictionary by changing its first element and adding any
      other item to its endx={1:3, 5:6}<br />
      x.update({1:4, 8:7, 4:4})<br />
      print(x)
    </p>
    <p>output: {1: 4, 5: 6, 8: 7, 4: 4}</p>
    <p>
      keys()Show all the keys in a dictionarya={1:2, 4:8}<br />
      a.keys()
    </p>
    <p>output: dict_keys([1, 4])</p>
    <p>
      values()Show all the values in a dictionarya={1:2, 4:8}<br />
      a.values()
    </p>
    <p>output: dict_values([2, 8])</p>
    <p>
      items()Display the keys and the values in a dictionarya={1:2, 4:8}<br />
      a.items()
    </p>
    <p>output: dict_items([(1, 2), (4, 8)])</p>
    <p>
      get(key)Get the value of an item in a dictionary by its keya={1:2, 4:8,
      3:5}<br />
      a.get(1)
    </p>
    <p>output: 2</p>
    <p>
      setdefault(key)Return the original value of an element to a
      dictionarya.setdefault(2)f={**a, **b}Merge two dictionariesa={‘x’:6,
      ‘y’:8}<br />
      b={‘c’:5, ‘d’:3}<br />
      f={**a, **y}<br />
      print(f)
    </p>
    <p>output:{‘x’: 6, ‘y’: 8, ‘c’: 5, ‘d’: 3}</p>
    <p>
      remove()Remove the first matching value of an element from a list without
      minding its indexa=[1, 3, 2, 4, 4, 1, 6, 6, 4]<br />
      a.remove(4)<br />
      print(a)
    </p>
    <p>output: [1, 3, 2, 4, 1, 6, 6, 4]</p>
    <p>
      memoryview(x)Access the internal buffers of an
      objecta=memoryview(object)bytes()Convert a memory buffer protocol into
      bytesbytes(a[0:2])bytearray()Return an array of
      bytesbytearray(object)#Write a single line of comment or prevent a line of
      code from being executed# Python regex cheat sheet""" "““Write a
      multi-line comment”““The Python regex cheat sheet is good for beginners<br />
      It’s equally a great refresher for experts”““<strong>Command Line</strong
      >pip install packageInstall an online librarypip install pandasvirtualenv
      nameUse virtaulenv to create a virtual environmentvirtualenv
      myprojectmkvirtualenv nameUse virtual environment wrapper to create
      virtual environmentmkvirtualenv myprojectpython file.pyRun the commands in
      a Python file”python my_file.pypip freezeList out all the installed
      packages in a virtual environmentpip freezepip freeze &gt; somefilesCopy
      all installed libraries in a single filepip freeze &gt;
      requirements.txtwhereFind the installation path of Pythonwhere
      python–versionCheck the version of a packagepython –version.exeRun a
      Python shellpython.exewith open(file, ‘w’)Write to an existing file and
      overwrite its existing contentwith open(‘regex.txt’, ‘w’) as wf:<br />
      wf.write(“Hello World!”)with open(file, ‘r’)Open a file as read-onlywith
      open(‘regex.txt’, ‘r’) as rf:<br />
      print(rf.read()with open(file, ‘a’)Write to a file without overwriting its
      existing contentwith open(‘regex.txt’, ‘a’) as af:<br />
      af.write(“\nHello Yes!”)file.closeClose a file if it’s not in
      useaf=open(‘regex.txt’)<br />
      af.closeexitExit the Python shellexit()
    </p>
    <p>
      <a href="https://www.makeuseof.com/python-regex-cheat-sheet/">Source</a>
    </p>
  </body>
</html>
